package com.starsea.book.ui.newpage.viewmodel

import android.app.Application
import android.content.Context
import android.text.TextUtils
import android.widget.TextView
import androidx.collection.arrayMapOf
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.SpanUtils
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.starsea.book.R
import com.starsea.book.base.BaseViewModel
import com.starsea.book.constant.AppConst
import com.starsea.book.constant.PreferKey
import com.starsea.book.help.http.newCallResponseBody
import com.starsea.book.help.http.okHttpClient
import com.starsea.book.help.http.postJson
import com.starsea.book.help.http.text
import com.starsea.book.ui.newpage.PrivateDealActivity
import com.starsea.book.ui.newpage.activity.FeedbackActivity
import com.starsea.book.ui.newpage.entity.BaseEntity
import com.starsea.book.ui.newpage.entity.FeedBackListEntity
import com.starsea.book.ui.newpage.entity.FlowContentEntity
import com.starsea.book.ui.newpage.entity.ImageSelEntity
import com.starsea.book.ui.newpage.entity.UserProfileEntity
import com.starsea.book.ui.newpage.entity.VipEntity
import com.starsea.book.ui.newpage.utils.gsonList
import com.starsea.book.ui.newpage.utils.gsonNormal
import com.starsea.book.utils.LogUtils
import com.starsea.book.utils.getPrefString
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.chromium.base.Callback
import splitties.init.appCtx
import java.io.File
import kotlin.collections.set

class UserViewModel(application: Application) : BaseViewModel(application) {

    val userProfileResult = MutableLiveData<BaseEntity<UserProfileEntity>>()
    val vipTcListResult = MutableLiveData<BaseEntity<MutableList<VipEntity>>>()
    val vipRightResult = MutableLiveData<MutableList<FlowContentEntity>>()
    val uploadImgResult = MutableLiveData<BaseEntity<String?>>()
    val uploadSucResult = MutableLiveData<BaseEntity<String?>>()
    val feedBackListResult = MutableLiveData<BaseEntity<FeedBackListEntity>>()
    val feedBackDetailsResult = MutableLiveData<BaseEntity<FeedBackListEntity.List>>()
    val updateUserInfoSucResult = MutableLiveData<BaseEntity<String?>>()
    fun getUserProfile() {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/customer/person"))
            }.text().let {

                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<UserProfileEntity> =
                    it.gsonNormal(UserProfileEntity::class.java)
                userProfileResult.postValue(entity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun updateUserProfile(custName: String = "", headerUrl: String = "", sex: Int = -1) {
        val map: MutableMap<String, String> = arrayMapOf()
        if (!TextUtils.isEmpty(custName))
            map["custName"] = custName
        if (!TextUtils.isEmpty(headerUrl))
            map["hedaUrl"] = headerUrl
        if (sex != -1)
            map["sex"] = sex.toString()
        val json = Gson().toJson(map)
        LogUtils.e(">>> ", "json  = " + json)
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/customer/updatePerson"))
                    .postJson(json)
            }.text().let {

                LogUtils.e(">>>", ">>.${it}")

                val baseEntity = BaseEntity<String?>()

                val objects = JsonParser.parseString(it).asJsonObject
                baseEntity.status = objects.get("status").asInt
                baseEntity.msg = objects.get("msg").asString
                updateUserInfoSucResult.postValue(baseEntity)
//                val entity: BaseEntity<UserProfileEntity> =
//                    it.gsonNormal(UserProfileEntity::class.java)
//                userProfileResult.postValue(entity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun getVipTcList() {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/member-order/findMemberThali"))
                    .post("".toRequestBody())
            }.text().let {

                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<VipEntity>> =
                    it.gsonList(VipEntity::class.java)
                vipTcListResult.postValue(entity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun uploadImg(fileName: String, filePath: String) {
        execute {
            okHttpClient.newCallResponseBody {

                val file = File(filePath);
                val fileName = "" + System.currentTimeMillis() + "_" + file.name;
                val requestBody: RequestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("module", "7")
                    .addFormDataPart("type", "1")
                    .addFormDataPart(
                        "file",
                        file.name,
                        RequestBody.create("image/png".toMediaTypeOrNull(), file)
                    )
                    .build()

                url(AppConst.BASE_URL.plus("front-api/upload/upload"))
                    .addHeader("token", appCtx.getPrefString(PreferKey.token) ?: "")
                    .post(requestBody)
            }.text().let {

//                {"status":"200","success":true,"msg":"操作成功","data":"https://blblkj.oss-cn-beijing.aliyuncs.com/novel/img/provide/65a6160fe4b08a9e82c8e4d5.png"}
                LogUtils.e(">>>", ">>.${it}")
                val baseEntity = BaseEntity<String?>()

                val objects = JsonParser.parseString(it).asJsonObject
                baseEntity.status = objects.get("status").asInt
                baseEntity.msg = objects.get("msg").asString
                baseEntity.data = objects.get("data").asString
                uploadImgResult.postValue(baseEntity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun uploadFeedback(content: String, imgs: String, qq: String, tel: String) {

        val map: MutableMap<String, String> = arrayMapOf()
        map["content"] = content
        map["imgs"] = imgs
        map["qq"] = qq
        map["tel"] = tel

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/customer-provide/provide_add"))
                    .postJson(Gson().toJson(map))
            }.text().let {

                LogUtils.e(":>>>", ">>.${it}")

                val baseEntity = BaseEntity<String?>()

                val objects = JsonParser.parseString(it).asJsonObject
                baseEntity.status = objects.get("status").asInt
                baseEntity.msg = objects.get("msg").asString
                uploadSucResult.postValue(baseEntity)


            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }


    fun getFeedBackList(pageNo: Int) {
        val map: MutableMap<String, String> = arrayMapOf()

        map["pageNo"] = pageNo.toString()
        map["pageSize"] = 10.toString()

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/customer-provide/page_list"))
                    .postJson(Gson().toJson(map))
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<FeedBackListEntity> =
                    it.gsonNormal(FeedBackListEntity::class.java)
                feedBackListResult.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun getFeedBackDetails(provideId: String) {

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/customer-provide/provide_detail?provideId=${provideId}"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<FeedBackListEntity.List> =
                    it.gsonNormal(FeedBackListEntity.List::class.java)
                feedBackDetailsResult.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun setVipHint(tvHint: TextView, mContext: Context) {
        tvHint.text = SpanUtils()
            .append("温馨提示\n")
            .append("1.若开通会员后10分钟内标识仍然没有点亮，请退出账号后重新登录进行尝试\n")
            .append("2.开通前请您查阅")
            .append("《特权服务协议》")
            .setForegroundColor(ContextCompat.getColor(mContext, R.color.color_2661F7))
            .setClickSpan(
                ContextCompat.getColor(
                    mContext,
                    R.color.color_2661F7
                ), false
            ) {
                mContext.startActivity<PrivateDealActivity> {
                    putExtra("type", "MEMBER")
                }
            }
            .append("\n3.VIP会员时长中，1个月=31天")
            .append("\n如有其他疑问，")
            .append("请前往帮助与反馈")
            .setForegroundColor(ContextCompat.getColor(mContext, R.color.color_2661F7))
            .setClickSpan(
                ContextCompat.getColor(
                    mContext,
                    R.color.color_2661F7
                ), false
            ) {
                mContext.startActivity<FeedbackActivity> {

                }
            }
            .create()

    }


    fun getVipRight() {
        val list: MutableList<FlowContentEntity> = arrayListOf()

        list.add(FlowContentEntity(content = "阅读无广告", resImg = R.mipmap.vip_1))
        list.add(FlowContentEntity(content = "听书无广告", resImg = R.mipmap.vip_2))
        list.add(FlowContentEntity(content = "全本下载\n无广告", resImg = R.mipmap.vip_3))
        list.add(FlowContentEntity(content = "双倍阅读金币", resImg = R.mipmap.vip_4))
        list.add(FlowContentEntity(content = "等级1.2倍加速", resImg = R.mipmap.vip_5))
        list.add(FlowContentEntity(content = "尊贵标识", resImg = R.mipmap.vip_6))
        list.add(FlowContentEntity(content = "更多权益", resImg = R.mipmap.vip_7))

        vipRightResult.postValue(list)

    }


    fun buyVip(thaliId: String, payType: Int, callback: Callback<String>) {
        // 创建表单构建器
        val formBody = FormBody.Builder()
            .add("thaliId", thaliId)
            .add("payType", payType.toString())
            .build()

        // 打印要发送的参数
        LogUtils.e(">>> 发送参数", ": thaliId=${thaliId}, payType=${payType}")

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/member-order/create"))
                    .post(formBody) // 使用表单作为请求体
            }.text().let {
                callback.onResult(it)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }
//    protected fun getRequestBody(js_request: Map<String?, Any?>?): RequestBody? {
//        return RequestBody.create(
//            Gson().toJson(js_request),
//            Media.parse.parse("application/json; charset=utf-8")
//        )
//    }

    fun getImgList(): MutableList<ImageSelEntity> {
        val list: MutableList<ImageSelEntity> = ArrayList<ImageSelEntity>()
        list.add(ImageSelEntity(ImageSelEntity.KEY_ORDER_IMAGE, null))
        return list
    }
}
